package info.manxi;

import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.pattern.Patterns;
import akka.util.Timeout;
import scala.concurrent.Await;
import scala.concurrent.Future;

import java.time.Duration;

public class PipeTest extends AbstractActor {


    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .matchEquals("", m -> {
                    ActorRef answer = getContext().system().actorOf(Props.create(AnswerActor.class, "answer"));
                    Future<Object> ask = Patterns.ask(answer, 3, 2000);

                    ActorRef worker = getContext().system().actorOf(Props.create(WorkerActor.class, "worker"));
                    Patterns.pipe(ask, getContext().dispatcher()).to(worker);

                    System.out.println("dp");
                })
                .build();
    }


    public static void main(String[] args) {
        ActorSystem system = ActorSystem.create("manxi-info");
        ActorRef ask = system.actorOf(Props.create(PipeTest.class), "AskTest");

        ask.tell("", ActorRef.noSender());
    }

    private static class AnswerActor extends AbstractActor {
        public AnswerActor(String s) {
            System.out.println(s);
        }

        @Override
        public Receive createReceive() {
            return receiveBuilder()
                    .match(Integer.class, i -> {
                        Thread.sleep(2000);
                        getSender().tell(i * i + i, getSelf());
                    })
                    .build();
        }

    }

    private static class WorkerActor extends AbstractActor {
        public WorkerActor(String s) {
            System.err.println(s);
        }

        @Override
        public Receive createReceive() {
            return receiveBuilder()
                    .matchAny(i -> {
                        System.out.println(i);
                        System.out.println(i);
                    })
                    .build();
        }

    }
}